package neolith.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

/**
 *
 */
public class EmptyRecyclerView extends RecyclerView {
  private View emptyView;
  private int headerCount, footerCount;

  public EmptyRecyclerView(@NonNull Context context) {
    super(context);
  }

  public EmptyRecyclerView(@NonNull Context context,
      @Nullable AttributeSet attrs) {
    super(context, attrs);
  }

  public EmptyRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs,
      int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  final private AdapterDataObserver observer = new AdapterDataObserver() {
    @Override
    public void onChanged() {
      checkIfEmpty();
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
      checkIfEmpty();
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
      checkIfEmpty();
    }
  };

  private void checkIfEmpty() {
    if (emptyView != null && getAdapter() != null) {
      final boolean emptyViewVisible = getAdapter().getItemCount() == headerCount + footerCount;
      emptyView.setVisibility(emptyViewVisible ? VISIBLE : GONE);
      setVisibility(emptyViewVisible ? GONE : VISIBLE);
    }
  }

  @Override
  public void setAdapter(Adapter adapter) {
    final Adapter oldAdapter = getAdapter();
    if (oldAdapter != null) {
      oldAdapter.unregisterAdapterDataObserver(observer);
    }
    super.setAdapter(adapter);
    if (adapter != null) {
      adapter.registerAdapterDataObserver(observer);
    }

    checkIfEmpty();
  }

  /**
   * Sets the view to show if the adapter is empty
   */
  public void setEmptyView(View emptyView) {
    this.emptyView = emptyView;
    checkIfEmpty();
  }

  public void setHeaderCount(int headerCount) {
    this.headerCount = headerCount;
  }

  public void setFooterCount(int footerCount) {
    this.footerCount = footerCount;
  }
}
